package za.co.smartmi.security;

import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import za.co.smartmi.model.SystemAccount;
import za.co.smartmi.model.SystemUserRole;
import za.co.smartmi.service.SystemAccountService;
import za.co.smartmi.service.exception.ServiceException;

public class Authenticator {

    private static final Logger log = Logger.getLogger(Authenticator.class);
    
    @Autowired
    private SystemAccountService accountService;

    /**
     * Return the account depending on the login provided by spring security.
     *
     * @return the account if found
     */
    protected SystemAccount obtainAccount(String login) {
        SystemAccount account;
        try {
            account = accountService.getSystemAccount(login.toUpperCase());
        } catch (ServiceException ex) {
            log.debug("ServiceException occurred: " + ex);
            account = null;
        }
        return account;
    }

    protected List<GrantedAuthority> buildGrantedAuthoritiesList(String userCode) {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        List<SystemUserRole> roles;
        try {
            roles = accountService.getUserRoles(userCode);
        } catch (ServiceException ex) {
            log.debug("ServiceException occurred: " + ex);
            roles = null;
        }

        if (roles != null) {
            for (SystemUserRole role : roles) {
				grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRole()));
            }
        }
        return grantedAuthorities;
    }

    protected AuthenticatedUserDetails buildUserDetails(String login, String password, boolean enabled, List<GrantedAuthority> authorities) {

        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        return new AuthenticatedUserDetails(login, password, enabled, accountNonExpired,
                credentialsNonExpired, accountNonLocked, authorities);

    }

    public boolean isPasswordValid(String storedPassword, String enteredPassword) {
        //entered password must be hashed so we can compare hashed pwd from db
        enteredPassword = encodePassword(enteredPassword);
        if (storedPassword == null || storedPassword.length() == 0) {
            return false;
        }
        if (enteredPassword == null || enteredPassword.length() == 0) {
            return false;
        }
        return storedPassword.trim().equals(enteredPassword.trim());
    }

    public static String getCurrentEnvironment() {
        String env = "au";
        env = env + "ORG";
        return env;
    }

    public String encodePassword(String password) {
        try {
            PasswordEncoder encoder = new ShaPasswordEncoder(256);
            return encoder.encodePassword(password, null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
